package com.qmerak.dao.impl;

import java.util.List;
import java.util.UUID;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.qmerak.dao.HibernateDao;
import com.qmerak.entity.MemberEntity;
import com.qmerak.entity.OrgEntity;

/**
 * @author shaohong.cheng
 * @date 2013-4-11
 */
@Repository
public class OrgDao extends HibernateDao<OrgEntity, String> {

	public OrgEntity add(OrgEntity entity) {
		entity.setId(UUID.randomUUID().toString());
		return super.add(entity);
	}

	@SuppressWarnings("unchecked")
	public OrgEntity orgOfManager(MemberEntity memberEntity) {
		Session session = this.sessionFactory.openSession();
		List<OrgEntity> orgEntities = session
				.createQuery("from OrgEntity where id=?")
				.setParameter(0, memberEntity.getUnionId()).list();
		session.close();
		if (orgEntities.isEmpty()) {
			return null;
		}
		return orgEntities.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<OrgEntity> getLowLevelOrg(OrgEntity orgEntity) {
		Session session = this.sessionFactory.openSession();
		List<OrgEntity> list = session
				.createQuery("from OrgEntity where parentid=?")
				.setParameter(0, orgEntity.getId()).list();
		session.close();
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<OrgEntity> getRootOrgs() {
		Session session = this.sessionFactory.openSession();
		List<OrgEntity> list = session
				.createQuery("from OrgEntity where parentid=?")
				.setParameter(0, "").list();
		session.close();
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<OrgEntity> queryByCondition(String condition) {
		String sql = "from OrgEntity";
		if (null != condition && !"".equals(condition)) {
			sql += " where " + condition;
		}
		Session session = this.sessionFactory.openSession();
		List<OrgEntity> list = session.createQuery(sql).list();
		session.close();
		return list;
	}

}
